package com.leetcode.array.binarysearch.demo2;

/**
 * @Author Zan
 * @Create 2024/5/7 23:11
 * @ClassName: Test2
 * @Description : https://leetcode.cn/problems/search-insert-position/description/  搜索插入位置
 */
public class Test2 {
    public static void main(String[] args) {

    }
}

// 暴力求解法
class Solution {
    public int searchInsert(int[] nums, int target) {
        // 返回被插入的索引 - 顺序数组
        for (int i = 0; i < nums.length; i++) {
            if (target <= nums[i]) {
                return i;
            }
        }
        return nums.length;
    }
}

// 二分
class Solution2 {
    public int searchInsert(int[] nums, int target) {
        // 返回被插入的索引 - 顺序数组
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            } else {
                return middle;
            }
        }
        return right + 1;
    }
}
